﻿using Dapper;
using ML.Entity;
using ML.IRepository;
using MySql.Data.MySqlClient;
using System.Linq;

namespace ML.Repository
{
    public class AdvertisementRepository : DBFactory, IAdvertisementRepository
    {
        public Pager<AdvertisementEntity> List(AdvertisementSearch advertisementSearch)
        {
            //组装调用存储过程参数
            var criteria = new PageCriteria() { TableName = "ml_advertisement" };
            if (!string.IsNullOrEmpty(advertisementSearch.Summary))
            {
                criteria.Conditions += string.Format(" AND Summary LIKE'%{0}%'", advertisementSearch.Summary);
            }

            criteria.PageIndex = advertisementSearch.pageindex;
            criteria.Field = @"Id,UrlPath,Type,Summary,CreateTime";
            criteria.PageSize = advertisementSearch.pagesize;
            criteria.SortName = "CreateTime";
            if (advertisementSearch.orderby)
            {
                criteria.Sort = "DESC";
            }
            else
            {
                criteria.Sort = "ASC";
            }

            //调用存储过程进行查询并且返回
            var list = GetPageData<AdvertisementEntity>(criteria);
            return list;
        }

        AdvertisementEntity IBaseRepository<AdvertisementEntity>.GetById(string id)
        {
            const string sql = @"SELECT * FROM ml_advertisement Where Id=@Id";
            using (_db)
            {
                return _db.Query<AdvertisementEntity>(sql, new { @Id = id }).FirstOrDefault();
            }
        }

        public bool Add(AdvertisementEntity entity)
        {
            const string sql = @"INSERT INTO ml_advertisement(Id,UrlPath,Type,Summary,CreateTime) VALUES (@Id,@UrlPath,@Type,@Summary,@CreateTime);";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Update(AdvertisementEntity entity)
        {
            const string sql = @"UPDATE ml_advertisement Set UrlPath=@UrlPath,Type=@Type,Summary=@Summary,CreateTime=@CreateTime WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Delete(AdvertisementEntity entity)
        {
            throw new System.NotImplementedException();
        }

        public bool Delete(string id)
        {
            const string sql = @"DELETE FROM ml_advertisement WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, new { @Id = id }) > 0)
                {
                    return true;
                }
                return false;
            }
        }
    }
}